package com.github.data_manage.controller

import cn.dev33.satoken.stp.StpUtil
import com.github.data_manage.common.CommonPage
import com.github.data_manage.common.CommonResult
import com.github.data_manage.common.CompaniesEnum
import com.github.data_manage.common.ResultCode
import com.github.data_manage.config.SystemException
import com.github.data_manage.dao.RoleDao
import com.github.data_manage.dao.UserDao
import com.github.data_manage.domain.po.User
import com.github.data_manage.domain.vo.ResetPasswordVo
import com.github.data_manage.domain.vo.UserPageParam
import com.github.data_manage.util.PageUtil
import io.swagger.v3.oas.annotations.Operation
import io.swagger.v3.oas.annotations.tags.Tag
import jakarta.transaction.Transactional
import jakarta.validation.constraints.NotNull
import org.springframework.data.jpa.domain.Specification
import org.springframework.util.StringUtils
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.*

/**
 *@author CHN
 *@since 2024-08-18 17:00
 */
@RestController
@RequestMapping("/user")
@Tag(name = "UserController", description = "用户管理")
class UserController(
    private val roleDao: RoleDao,
    private val userDao: UserDao
) {

    @PostMapping("/saveOrUpdate")
    @Operation(description = "新增/编辑用户")
    @Transactional(rollbackOn = [Exception::class])
    fun saveOrUpdate(@RequestBody @Validated user: User): CommonResult<String> {
        userDao.save(user)
        return CommonResult.success(ResultCode.SUCCESS.message)
    }


    @Operation(description = "删除用户")
    @DeleteMapping(value = ["/delete"])
    @Transactional(rollbackOn = [Exception::class])
    fun deleteCompanyById(@RequestBody userIds: Collection<Int>): CommonResult<String> {
        userDao.findAllById(userIds).forEach { user ->
            StpUtil.logout(user.id)
        }
        userDao.deleteAllById(userIds)
        return CommonResult.success(CompaniesEnum.DELETE_SUCCESS.message);
    }

    @Operation(description = "角色列表")
    @RequestMapping(value = ["/list"], method = [RequestMethod.POST])
    @ResponseBody
    fun getCompanyList(@Validated @RequestBody userPageParam: UserPageParam): CommonResult<CommonPage<User>> {
        val condition = Specification<User> { root, _, builder ->
            if (StringUtils.hasText(userPageParam.userName)) {
                return@Specification builder.like(
                    root.get<String>("name"),
                    "%${userPageParam.userName}%"
                )
            }
            return@Specification builder.isNotNull(root.get<Int>("id"))
        }
        val page = PageUtil.buildJpaPage<User>(userPageParam.pageNum, userPageParam.pageSize)

        return CommonResult.success(
            CommonPage.restPage(userDao.findAll(condition, page))
        )
    }

    @Operation(description = "重设用户密码")
    @PutMapping("/resetPassword")
    fun resetPassword(@Validated @NotNull @RequestBody resetPasswordVo: ResetPasswordVo): CommonResult<String?> {
        if (resetPasswordVo.newPasswordCheck != resetPasswordVo.newPassword) {
            return CommonResult.failed("前后输入的密码不一致")
        }
        val user = userDao.findById(resetPasswordVo.userId).orElseThrow { SystemException("用户不存在") }
        user.password = resetPasswordVo.newPassword
        userDao.save(user)
        StpUtil.logout(user.id)

        return CommonResult.success(ResultCode.SUCCESS.message)
    }

}
